#include "ShipManage.h"
#include <QDebug>
#include "LonLatUtil.h"
#include "gtime.h"
#include "mylogger.h"
#include "dbsystemlog.h"

using namespace ns_yht;

ShipManage *ShipManage::g_shipManage = nullptr;

ShipManage::ShipManage()
{
    g_shipManage = this;
    DbSystemLog db;
    db.save(GTime::getUtcTime_s(), SystemEventType::turnOn, "系统启动", false);
    db.removeBefore(GTime::getUtcTime_s() - 86400 * 366);
}

ShipManage::~ShipManage()
{
    g_shipManage = nullptr;
    DbSystemLog db;
    db.save(GTime::getUtcTime_s(), SystemEventType::turnOff, "系统退出", false);
}

ShipManage *ShipManage::instance()
{
    return g_shipManage;
}

void ShipManage::startThread(QThread &thread)
{
    if (thread.isRunning())
        return;
    moveToThread(&thread);

    thread.start();
}

const QMap<quint64, QSharedPointer<ModelShip>> &ShipManage::getShipList() const
{
    return m_shipList;
}

QSharedPointer<ModelShip> ShipManage::getOwnShip() const
{
    return m_ownShip;
}

QSharedPointer<ModelShip> ShipManage::getSearchedShip() const
{
    return m_searchedShip;
}

const QVector<QPair<quint64, QString>> &ShipManage::getSearchedResult() const
{
    return m_searchedResult;
}

// const QVector<QSharedPointer<ModelShip>> &ShipManage::getDangerousShipList() const
// {
//     return m_dangerousShipList;
// }

void ShipManage::setShowInner(bool ishow)
{
    if (m_showInner == ishow)
        return;
    m_showInner = ishow;
    emit innerShipsChanged();
}

void ShipManage::setShowOuter(bool ishow)
{
    if (m_showOuter == ishow)
        return;
    m_showOuter = ishow;
    emit shipsChanged();
}

bool ShipManage::showInner() const
{
    return m_showInner;
}

bool ShipManage::showOuter() const
{
    return m_showOuter;
}

void ShipManage::onEhhMapChanged()
{
    m_elapsedTimer.restart();
    emit shipsChanged(); // 按当前位置先重画，再从服务器获取
    // // qInfo() << "ShipManage::onEhhMapChanged()======================================";

    // if (m_timerId == 0)
    //     m_timerId = startTimer(500);
    // m_startCount = true;
}

int ShipManage::getPanelId() const
{
    return m_panelId;
}

bool ShipManage::isBusy() const
{
    return false;
}

bool ShipManage::ownValid() const
{
    return !m_ownShip.isNull() && LonLatUtil::isValid(m_ownShip->lat, m_ownShip->lon);
}

int ShipManage::getAisShipCount() const
{
    return m_aisCount;
}

int ShipManage::getArpaShipCount() const
{
    return m_arpaCount;
}

int ShipManage::getShipCount(int &aisCount, int &arpaCount) const
{
    aisCount = m_aisCount;
    arpaCount = m_arpaCount;
    return m_shipList.size();
}

double ShipManage::getRadius_nm() const
{
    return m_radius_nm;
}

void ShipManage::onRadiusChanged(double radius_nm)
{
    // if (m_radius_nm == radius_nm)
    //     return;
    m_radius_nm = radius_nm;
    m_radius = radius_nm * 1852.0;
}

// void ShipManage::onRadiusChanged(double radius_nm)
// {
//     m_radius = radius_nm * 1852.0;
// }

void ShipManage::latlonAdjust(QSharedPointer<ModelShip> ship, int type)
{
    // int x = 0, y = 0;
    // // if (type != 2)
    // {
    //     ship->to_bow = ALLSETTINGS.systemSetting.ownshipOutline.ccrp.A;
    //     ship->to_port = ALLSETTINGS.systemSetting.ownshipOutline.ccrp.C;
    //     ship->to_starboard = ALLSETTINGS.systemSetting.ownshipOutline.ccrp.D;
    //     ship->to_stern = ALLSETTINGS.systemSetting.ownshipOutline.ccrp.B;
    // }

    // if (type == 0) // BD
    // {
    //     if (ALLSETTINGS.systemSetting.ownshipOutline.gnss1.type == 0)
    //     {
    //         x = ALLSETTINGS.systemSetting.ownshipOutline.gnss1.x;
    //         y = ALLSETTINGS.systemSetting.ownshipOutline.gnss1.y;
    //     }
    //     else if (ALLSETTINGS.systemSetting.ownshipOutline.gnss2.type == 0)
    //     {
    //         x = ALLSETTINGS.systemSetting.ownshipOutline.gnss2.x;
    //         y = ALLSETTINGS.systemSetting.ownshipOutline.gnss2.y;
    //     }
    // }
    // else if (type == 1) // GP
    // {
    //     if (ALLSETTINGS.systemSetting.ownshipOutline.gnss1.type == 1)
    //     {
    //         x = ALLSETTINGS.systemSetting.ownshipOutline.gnss1.x;
    //         y = ALLSETTINGS.systemSetting.ownshipOutline.gnss1.y;
    //     }
    //     else if (ALLSETTINGS.systemSetting.ownshipOutline.gnss2.type == 1)
    //     {
    //         x = ALLSETTINGS.systemSetting.ownshipOutline.gnss2.x;
    //         y = ALLSETTINGS.systemSetting.ownshipOutline.gnss2.y;
    //     }
    // }
    // else if (type == 2) // AIS
    // {
    //     if (ALLSETTINGS.systemSetting.ownshipOutline.gnss1.type == 2)
    //     {
    //         x = ALLSETTINGS.systemSetting.ownshipOutline.gnss1.x;
    //         y = ALLSETTINGS.systemSetting.ownshipOutline.gnss1.y;
    //     }
    //     else if (ALLSETTINGS.systemSetting.ownshipOutline.gnss2.type == 2)
    //     {
    //         x = ALLSETTINGS.systemSetting.ownshipOutline.gnss2.x;
    //         y = ALLSETTINGS.systemSetting.ownshipOutline.gnss2.y;
    //     }
    // }

    // double angle = QYHHGeometry::radiansToDegrees(atan2(y, x));
    // if (y > 0)
    //     angle = 270 - angle;
    // else if (y < 0 && x > 0)
    //     angle = 360 - abs(angle);
    // else if (y < 0 && x < 0)
    //     angle = abs(angle) - 90;
    // Coordinate coor = QYHHGeometry::destination(Coordinate(ship->lat, ship->lon), sqrt(x * x + y * y), angle - ship->getAngle(), QYHHGeometry::METERS);
    // ship->lat = coor.first;
    // ship->lon = coor.second;
}

void ShipManage::onSetOwnshipCoordinate(double lat, double lon)
{
    if (!m_ownShip.isNull())
    {
        m_ownShip->lat = lat;
        m_ownShip->lon = lon;
        m_ownShip->time = GTime::getUtcTime_s();
        emit ownShipChanged(true);
    }
}

void ShipManage::onOwnshipMmsiChanged(quint64 mmsi)
{
    if (!m_ownShip.isNull() && m_ownShip->mmsi == mmsi)
        return;

    if (m_shipList.contains(mmsi))
    {
        m_ownShip.clear();
        m_ownShip = m_shipList[mmsi];
        m_shipList.remove(mmsi);
    }
    else
    {
        if (m_ownShip.isNull())
            m_ownShip.reset(new ModelShip);
        m_ownShip->mmsi = mmsi;
    }
}

const double ShipManage::getDepth() const
{
    return m_depth;
}

const double ShipManage::getDraught() const
{
    return m_draught;
}

const int ShipManage::getPosState() const
{
    return m_posState;
}

// 检索m_shipCollisionMap，找出tcpa最大的条目对应的mmsi
quint64 ShipManage::getMaxTcpaShipFromCollisionMap(double &tcpa) const
{
    quint64 mmsi = 0;
    tcpa = -10;
    for (auto it = m_shipCollisionMap.begin(); it != m_shipCollisionMap.end(); ++it)
    {
        if (it.value().tcpa > tcpa)
        {
            tcpa = it.value().tcpa;
            mmsi = it.key();
        }
    }
    return mmsi;
}

const QMap<quint64, ShipManage::SimpleShipInfo> &ShipManage::getShipCollisionMap() const
{
    return m_shipCollisionMap;
}

const CoordinatesCollection &ShipManage::getAlertArea() const
{
    return m_alertAreas;
}

void ShipManage::ensure(quint64 mmsi, bool isEnsured)
{
    if (m_shipCollisionMap.contains(mmsi))
    {
        m_shipCollisionMap[mmsi].ensured = isEnsured;
        if (GLOG)
            GLOG->debug("ensure ship: {}", mmsi);
    }
}
